package com.example.wuqiu.utils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

public class DateUtils {
    private static final SimpleDateFormat fullFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    private static final SimpleDateFormat yearFormat = new SimpleDateFormat("yyyy");
    private static final SimpleDateFormat monthDayFormat = new SimpleDateFormat("MM-dd");
    private static final SimpleDateFormat timeFormat = new SimpleDateFormat("HH:mm");
    private static final SimpleDateFormat yearMonthDayFormat = new SimpleDateFormat("yyyy-MM-dd");

    public static String formatDate(String dateStr, boolean showTime) {
        try {
            Date date = fullFormat.parse(dateStr);
            Calendar inputCal = Calendar.getInstance();
            inputCal.setTime(date);
            Calendar now = Calendar.getInstance();

            // 获取时间部分
            String timePart = showTime ? " " + timeFormat.format(date) : "";

            // 判断是否是今天
            if (isSameDay(inputCal, now)) {
                return "今天" + timePart;
            }

            // 判断是否是昨天
            now.add(Calendar.DAY_OF_YEAR, -1);
            if (isSameDay(inputCal, now)) {
                return "昨天" + timePart;
            }

            // 判断是否在本周内
            now.add(Calendar.DAY_OF_YEAR, 1); // 恢复今天
            int weekOfYear = now.get(Calendar.WEEK_OF_YEAR);
            int year = now.get(Calendar.YEAR);
            if (inputCal.get(Calendar.WEEK_OF_YEAR) == weekOfYear && inputCal.get(Calendar.YEAR) == year) {
                String[] weekDays = {"周日", "周一", "周二", "周三", "周四", "周五", "周六"};
                String weekDay = weekDays[inputCal.get(Calendar.DAY_OF_WEEK) - 1];
                return weekDay + timePart;
            }

            // 判断是否是今年
            if (inputCal.get(Calendar.YEAR) == now.get(Calendar.YEAR)) {
                return monthDayFormat.format(date) + timePart;
            }

            // 不是今年
            return yearMonthDayFormat.format(date) + timePart;
        } catch (ParseException e) {
            e.printStackTrace();
            return "Invalid Date";
        }
    }

    private static boolean isSameDay(Calendar cal1, Calendar cal2) {
        return cal1.get(Calendar.YEAR) == cal2.get(Calendar.YEAR) &&
                cal1.get(Calendar.DAY_OF_YEAR) == cal2.get(Calendar.DAY_OF_YEAR);
    }
    public static void main(String[] args) {
        System.out.println(formatDate("2025-03-20 14:30:00", false));
        System.out.println(formatDate("2025-03-19 14:30:00", true));
        System.out.println(formatDate("2025-03-18 14:30:00", true));
        System.out.println(formatDate("2025-02-20 14:30:00", true));
        System.out.println(formatDate("2024-10-10 14:30:00", true));
    }
}
